package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import groovy.json.JsonOutput
import org.springframework.security.access.annotation.Secured

@Secured(['ROLE_ADMINISTRATOR'])
@Transactional(readOnly = true)
class ProductController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond Product.findAll([sort: "modifiedDate", order: "desc"]), model: [productCount: Product.count()]
    }

    def show(Product product)
    {
        def attachmentList = Attachment.findAll("from Attachment where product.id = ?", [product.id])
        respond product, model: [attachmentList: attachmentList]
    }

    def create()
    {
        respond new Product(params)
    }

    @Transactional
    def save(Product product)
    {
        if (product == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (product.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond product.errors, view: 'create'
            return
        }

        product.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'product.label', default: 'Product'), product.id])
                redirect product
            }
            '*' { respond product, [status: CREATED] }
        }
    }

    def edit(Product product)
    {
        respond product
    }

    @Transactional
    def update(Product product)
    {
        if (product == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (product.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond product.errors, view: 'edit'
            return
        }

        product.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'product.label', default: 'Product'), product.id])
                redirect product
            }
            '*' { respond product, [status: OK] }
        }
    }

    @Transactional
    def delete(Product product)
    {

        if (product == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        product.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'product.label', default: 'Product'), product.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def searchProduct()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        def name = params["name"]
        String sql = "from Product as u where 1=1"
        if (name)
        {
            sql += " and u.name like '%${name}%'"
        }

        def type = params['type']
        if (type)
        {
            sql += " and u.type.name like '%${type}%'"
        }

        sql += ' order by createdDate desc'

        println "sql:" + sql

        def max = params.max
        def offset = params.offset

        def list = Product.findAll(sql, [max: max, offset: offset])
        def list1 = Product.findAll(sql)
        def count = list1.size()

        respond list, model: [productCount: count, params: params], view: 'index'
    }

    @Secured(['permitAll'])
    def appQueryproductByType()
    {
        def json = request.JSON
        println "************************* appQueryproductByType ***************************"
        println json

        def productList = []
        def productTypeList = ProductType.findAllByActive(true)
        productTypeList.each
        {
            def list = Product.findAllByTypeAndActive(it, true, [sort: "modifiedDate", order: "desc"])
            productList.add(list)
        }

        println productList

        def banners = Attachment.findAllByType(AttachmentType.findByName("产品LOGO"))

        def resultMap = [:]
        resultMap.put("productList", productList)
        resultMap.put("banners", banners)

        render resultMap as JSON
        return
    }

    @Secured(['permitAll'])
    def appQueryAllproduct()
    {
        def json = request.JSON
        println "************************* appQueryAllproduct ***************************"
        println json

        render Product.findAllByActive(true, [sort: "modifiedDate", order: "desc"]) as JSON
        return
    }

    @Secured(['permitAll'])
    def getProductInfoById()
    {
        def json = request.JSON
        println "************************* getProductInfoById ***************************"
        println json

        def productId = json["productId"]
        if (!productId)
        {
            def errors = [errorCode: 4001, errorMessage: "产品标识不能为空"]
            render JsonOutput.toJson(errors), status: 400
            return
        }
        
        def product = Product.findById(productId)
        if (!product)
        {
            def errors = [errorCode: 4002, errorMessage: "产品标识不正确"]
            render JsonOutput.toJson(errors), status: 400
            return
        }

        render product as JSON
        return
    }

    @Secured(['permitAll'])
    @Transactional
    def setToMainPicture(Attachment attachment)
    {
        def product = attachment?.product
        product.imageUrl = attachment.fileUrl
        product.save flush: true

        redirect controller: "product", action: "show", method: "GET", id: product?.id
        return
    }

    @Secured(['permitAll'])
    @Transactional
    def deleteAttachment(Attachment attachment)
    {

        if (attachment?.fileUrl == attachment?.product?.imageUrl) 
        {
            flash.message = "该图片为产品主图片，不允许删除！"
            redirect controller: "product", action: "show", method: "GET", id: attachment?.product?.id
            return
        }
        else
        {
            attachment.delete flush: true
            redirect controller: "product", action: "show", method: "GET", id: attachment?.product?.id
            return
        }
    }

    @Secured(['permitAll'])
    @Transactional
    def setToMainProduct(ProductItem productItem)
    {
        if (productItem.active) 
        {
            def product = productItem?.product
            product.price = productItem.price
            product.productItem = productItem
            product.save flush: true

            redirect controller: "product", action: "show", method: "GET", id: productItem?.product?.id
            return
        }
        else
        {
            flash.message = "该产品失效状态，不允许设置为默认产品！"
            redirect controller: "product", action: "show", method: "GET", id: productItem?.product?.id
            return
        }
    }

    @Secured(['permitAll'])
    @Transactional
    def changeActive(ProductItem productItem)
    {
        if (productItem?.active && productItem.product.productItem == productItem)
        {
            flash.message = "该产品为默认产品，不允许设置为失效状态！"
            redirect controller: "product", action: "show", method: "GET", id: productItem?.product?.id
            return
        }
        else
        {
            productItem.active = !productItem?.active
            productItem.save flush: true

            redirect controller: "product", action: "show", method: "GET", id: productItem?.product?.id
            return
        }
    }
}
